import { secret_key } from '../config/secret'
import { handleCreateToken, update } from '../utils'
import { Context } from 'koa'
import jwt from 'jsonwebtoken'

export const tokenHandler = async (ctx: Context, next: () => Promise<void>) => {
  try {
    await next()
    handleRefreshToken(ctx)
  } catch (err: any) {
    ctx.body = {
      message: err.status === 401 ? '登录失效' : err.message,
      code: err.status
    }
  }
}

const handleRefreshToken = (ctx: Context) => {
  let token = ctx.cookies.get('token')
  if (!token) return
  const payload = jwt.verify(ctx.cookies.get('token') || '', secret_key) as { username: string; exp: number }
  const now = Math.floor(Date.now() / 1000)

  // 剩余时间不足30分钟时刷新
  if (payload.exp - now < 1800) {
    handleCreateToken(ctx, payload.username)
  }
}
